package com.cskaoyan.day7._01_example;

import java.util.*;

/**
 * 最终业务代码的关键：
 * 1.你需要遍历，使用合适的容器来存
 * List<> Map<></>
 * @author Common-zhou
 * @since 2023-03-06 09:36
 */
public class Demo1 {
    public static void main(String[] args) {
        List<Teacher> teachers = generateTeachers();
        List<Student> students = generateStudents();

        // List<Grade>

        // 最终要的数据  Grade{
        // Teacher   List<Student>

        // 1.遍历学生  id  name age  teacherId
        // 2.使用Map组装  key是teacherId  value是学生的List
        // 3.遍历老师。在通过Map拿到学生的List

        Map<Integer, List<Student>> studentMap = new HashMap<>();
        for (Student student : students) {
            List<Student> studentList = studentMap.get(student.getTeacherId());
            // studentList有几种情况？
            // null    之前就有
            if (studentList == null) {
                // 如果是第一次进来，初始化一下
                studentList = new ArrayList<>();
            }

            studentList.add(student);

            // 把数据更新到Map中去
            studentMap.put(student.getTeacherId(), studentList);
        }

        // studentMap   teacherId, 对应的Student的列表
        // 可以打印验证一下
        List<Grade> grades = new ArrayList<>();
        for (Teacher teacher : teachers) {
            Integer teacherId = teacher.getId();

            // 只要拿到teacherId的信息，我们就可以拿到所有的学生列表
            List<Student> students1 = studentMap.get(teacherId);

            Grade grade = new Grade();
            grade.teacher = teacher;
            grade.students = students1;

            grades.add(grade);
        }

        // 最终的数据 在grades里面

        for (Grade grade : grades) {
            System.out.println(grade);
            System.out.println("--------------------------------");
        }


    }

    private static List<Teacher> generateTeachers() {
        List<Teacher> teachers = new ArrayList<>();
        Random random = new Random();

        // 循环5次 。生成了5个老师
        for (int i = 0; i < 5; i++) {
            Teacher teacher = new Teacher();
            teacher.setId(i);
            // 0  -- 4
            teacher.setName("teacher_" + i);
            // 35 + [0,4] == > 35,39
            teacher.setAge(35 + random.nextInt(5));

            teachers.add(teacher);
        }

        return teachers;
    }

    private static List<Student> generateStudents() {
        List<Student> students = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            Student student = new Student();

            student.setId(i);
            // 0  -- 4
            student.setTeacherId(i % 5);
            student.setName("student" + i);
            student.setAge(15);

            students.add(student);
        }

        return students;
    }

}
